package com.android.ClientApp;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.Socket;

import com.java.serverpackage.MessagePacket;

public class NetworkHandling {
	private static ObjectOutputStream outToServer = null;
	private static ObjectInputStream inFromServer = null;
	private static Socket clientSocket = null;
	private static Object msg = null;
	
    //private static int server_port = 5163;
	//private static String server_ip = new String("129.16.184.93");

	// Establish a connection to server
	public static void establishConnection(final String server_ip,final int server_port) {
    	new Thread(new Runnable() { public void run() {
	    	try {
				clientSocket = new Socket(server_ip,server_port);
				outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
				inFromServer = new ObjectInputStream(clientSocket.getInputStream());
			} catch (Exception e) {
			}
		}
	}).start();
	}
	
	// Send a message packet to server
	public static void writeToServer(MessagePacket msg) {
		try {
			outToServer.flush();
			outToServer.writeObject(msg);
		} catch (IOException e) {
		}
	}
	
	// Receive a message packet from server
	public static MessagePacket readFromServer() {
		msg = null;
		while(msg == null) {
			try {
				
				msg = inFromServer.readObject();
				if(msg != null)
					return (MessagePacket) msg;
			} catch (NullPointerException e){
			} catch (OptionalDataException e) {
			} catch (ClassNotFoundException e) {
			} catch (IOException e) {
			}
		}
		
		return null;
	}
	
	// Disconnect from server
	public static void disconnect() {
		try {
			outToServer.close();
			inFromServer.close();
			clientSocket.close();		
		} catch (IOException e) {
		}
	}
}
